package cn.itacst.upload;

import cn.itacst.utils.FileUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class UploadServlet3 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//request.setCharacterEncoding("utf-8");
		//1）	将DiskFileItemFactory对象绑定到ServletFIleUpload对象
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//设置缓存，3M
		factory.setSizeThreshold(1024*1024*3);
		//设置临时文件的存储位置
		factory.setRepository(new File("c:/temp"));
		//      创建ServletFIleUpload对象
		ServletFileUpload fileUpload = new ServletFileUpload(factory);
		//2）	ServletFIleUpload对象解析request对象
		//在解析request对象之前判断，当前的请求是否是一个文件上传的请求
		if(!fileUpload.isMultipartContent(request)){
			//不是文件上传的请求
			request.getRequestDispatcher("/").forward(request, response);
			return;
		}
		
		try {
			//设置解决中文乱码问题
			fileUpload.setHeaderEncoding("UTF-8");
			//3）	Request对象中的数据，最终会被解析成一个一个的FileItem对象。
			List<FileItem> list = fileUpload.parseRequest(request);
			//遍历集合，拿出数据
			for (FileItem fileItem : list) {
				//判断当前的fileItem（input输入框）是不是一个普通字段
				if(fileItem.isFormField()){
					//是一个普通字段
					String fieldName = fileItem.getFieldName();
					System.out.println("fieldName==="+fieldName);
					String value = fileItem.getString();
					System.out.println("value==="+value);
				}else{
					//不是普通字段的情况
					//确认向硬盘写出的路径，如何获取upload文件的路径
					String realPath = getServletContext().getRealPath("/uploadFolder");
					System.out.println("realPath===="+realPath);
					//获取文件名
					String fileName = fileItem.getName();
					
					//InputStream inputStream = fileItem.getInputStream();
					//使用UUID来保证文件名不重复
					String uuid = UUID.randomUUID().toString();
					//fileName要在后面，文件的后缀名，必须要在最后
					// info.txtfsdfsdfasfds
					fileName = uuid +"_"+ fileName;
					//进行目录分离
					String dir = FileUtils.getDir(fileName);
					//先要判断该目录是否存在
					File file2 = new File(realPath+dir);
					if(file2.exists()){
						//神马都不做
					}else{
						//创建文件目录
						file2.mkdirs();
					}
					File file = new File(realPath+dir,fileName);
					//向服务器硬盘写出数据
					try {
						fileItem.write(file);
						//保证临时文件可以删除
						fileItem.delete();
					} catch (Exception e) {
						e.printStackTrace();
						//保证临时文件可以删除
						fileItem.delete();
					}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		response.setContentType("text/html;charset=utf-8");
		String content = "你好,我来自UploadServlet3";

		String prefix="<font size='4' color='red'>";
		String postfix="</font>";
		String responseContent=prefix+content+postfix;
		response.getWriter().print(responseContent);

		System.out.println("----------------------------UploadServlet3 结束------------------------------");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
